var formidable = require('formidable'),
  util = require('util'),
  http = require('http'),
  fs = require('fs'),
  url = require('url');


http.createServer(function(req, res) {
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.write('receive upload:\n');
      var file = files.upload;
      var originalName = file.name;
      var fileName = fields.title + originalName.substring(originalName.indexOf('.'));
      var readPath = file.path;
      // 可读流
      var readerStream = fs.createReadStream(readPath);
      // 可写流
      var writerStream = fs.createWriteStream('files/' + fileName);
      readerStream.pipe(writerStream);
      res.end(util.inspect({ fields: fields, files: files }));
    });
    return;
  }
  res.writeHead(200, { 'Content-Type': 'text/html' });
  var readPath = __dirname + '/' + url.parse('form.html').pathname;
  var formPage = fs.readFileSync(readPath, 'utf8');
  res.end(formPage);
}).listen(3000);
console.log('server start at http://localhost:3000');
